package beanpay

import (
	"gitee.com/micro-plat/fas/modules/const/enum"
	"gitee.com/micro-plat/fas/modules/sdkdb"
	"github.com/asaskevich/govalidator"
	"github.com/micro-plat/beanpay/beanpay"
	"github.com/micro-plat/lib4go/errs"
)

//UpChannelRefund 上游渠道退款
func UpChannelRefund(param *UpRefund) error {

	// 验证参数
	if b, err := govalidator.ValidateStruct(param); !b {
		return errs.NewErrorf(406, "BPay:UpChannelRefund:govalidator.参数验证错误err:%+v,param:%+v", err, param)
	}

	// 获取数据操作对象
	_, trans, err := sdkdb.GetDBTrans(nil)
	if err != nil {
		return err
	}

	// 渠道账户扣款
	if param.UpRefundAmount > 0 {
		_, err := beanpay.GetAccount(param.Ident, enum.AccountGroups.UpChannel).RefundAmount(
			trans, param.UpChannelNo, param.TradeRefundNo, param.TradeDeliveryNo, beanpay.TPTrade, param.UpRefundAmount, param.Memo)
		if err != nil {
			trans.Rollback()
			return err
		}
	}

	// 佣金退款
	if param.UpRefundCommissionAmount != 0 {
		_, err := beanpay.GetAccount(param.Ident, enum.AccountGroups.UpCommission).DrawingAmount(
			trans, param.UpChannelNo, param.TradeRefundNo, param.UpRefundCommissionAmount, param.Memo)
		if err != nil {
			trans.Rollback()
			return err
		}
	}

	// 服务费退款
	if param.UpRefundServiceAmount != 0 {
		_, err := beanpay.GetAccount(param.Ident, enum.AccountGroups.UpService).DrawingAmount(
			trans, param.UpChannelNo, param.TradeRefundNo, param.UpRefundServiceAmount, param.Memo)
		if err != nil {
			trans.Rollback()
			return err
		}
	}
	trans.Commit()
	return nil
}
